<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { User, Lock } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { useTokenStore } from "@/stores/token";
import { getStudentInfoService, studentLoginService } from "@/api/student.js";
import { adminLoginService, getAdminInfoService } from "@/api/admin.js";
import { getTeacherInfoService, teacherLoginService } from "@/api/teacher";
import useUserStore from "@/stores/userStore.js";
// import useUserStore from "@/stores/userStore.js";
const router = useRouter();
const userStore = useUserStore();
const tokenstore = useTokenStore();
// const userStore = useUserStore();
const LoginData = ref({
  username: "",
  password: "",
});
const user = ref("管理员");
const formRef = ref(null);

const getAdminInfo = async () => {
  let result = await getAdminInfoService(LoginData.value.username);
  //数据存储到pinia中
  await userStore.setInfo(result.data);
};
const getStudentInfo = async () => {
  let result = await getStudentInfoService(LoginData.value.username);
  //数据存储到pinia中
  await userStore.setInfo(result.data);
};
const getTeacherInfo = async () => {
  let result = await getTeacherInfoService(LoginData.value.username);
  //数据存储到pinia中
  await userStore.setInfo(result.data);
};

const login = async () => {
  // 使用表单验证
  formRef.value.validate(async (valid) => {
    if (valid) {
      let result;
      try {
        switch (user.value) {
          case "管理员":
            result = await adminLoginService(LoginData.value);
            break;
          case "教师":
            result = await teacherLoginService(LoginData.value);
            break;
          case "学生":
            result = await studentLoginService(LoginData.value);
            break;
          default:
            throw new Error("无效的用户类型");
        }

        if (result.code === 0) {
          ElMessage.success(result.message ? result.message : "登录成功");
        } else {
          throw new Error("登录失败，未收到服务器响应");
        }

        if (result && result.data) {
          tokenstore.setToken(result.data);
          if (user.value === "管理员") {
            await getAdminInfo();
            await router.push("/admin");
          } else if (user.value === "教师") {
            await getTeacherInfo();
            await router.push("/teacher");
          } else if (user.value === "学生") {
            await getStudentInfo();
            await router.push("/student");
          }
        }
      } catch (error) {
        ElMessage.error(error.message ? error.message : "服务异常");
      }
    } else {
      console.log("表单验证失败");
      return false;
    }
  });
};

const rule = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 1, max: 16, message: "长度为1~16非空字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 1, max: 16, message: "长度为1~16非空字符", trigger: "blur" },
  ],
};
</script>

<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <el-form
        ref="formRef"
        size="large"
        autocomplete="off"
        :model="LoginData"
        :rules="rule"
      >
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            :prefix-icon="User"
            placeholder="请输入用户名"
            v-model="LoginData.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            name="password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
            v-model="LoginData.password"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <div class="my-2 flex items-center text-sm">
            <el-radio-group v-model="user" class="ml-4">
              <el-radio value="管理员">管理员</el-radio>
              <el-radio value="学生">学生</el-radio>
              <el-radio value="教师">教师</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            class="button"
            type="primary"
            auto-insert-space
            @click="login"
            >登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
/* 样式 */
.login-page {
  height: 100vh;
  background-color: #fff;
  overflow: hidden;

  .bg {
    background: url("@/assets/login_bg.jpg") no-repeat center / cover;
    border-radius: 20px 20px 20px 20px;
    height: calc(100% - 20px); // 确保高度为父元素的100%，减去上下各10px的边距
    margin: 10px 10px; // 上下各增加10px的边距
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
